package com.feihong.txgw.ui.activity.product;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.KeyboardUtils;
import com.feihong.txgw.R;
import com.feihong.txgw.adapter.HotSearchHistoryAdapter;
import com.feihong.txgw.adapter.product.HotSearchGdAdapter;
import com.feihong.txgw.inter.contract.product.IHotSearchContract;
import com.feihong.txgw.message.LoginMessage;
import com.feihong.txgw.model.bean.searchList.HisToryEntity;
import com.feihong.txgw.model.bean.user.HotSearchDataModel;
import com.feihong.txgw.tx_precenter.HotSearchMainPrecenter;
import com.feihong.txgw.ui.mvp.BaseMVPCompateActivity;
import com.feihong.txgw.ui.mvp.precenter.AbBasePrecenter;
import com.feihong.txgw.utils.HistoryUtil;


import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.pedant.SweetAlert.SweetAlertDialog;

/**
 * Created by Sabirjan on 2017/6/30.
 * TXGWApp.
 * 飞宏电子
 * 历史搜索页面
 */

public class HotSearchActivity extends BaseMVPCompateActivity<IHotSearchContract.AbHotSearchMainPrecenter> implements IHotSearchContract.IHotSearchMainView {

    @BindView(R.id.back)
    RelativeLayout back;
    @BindView(R.id.et_search)
    EditText etInputCitys;
    @BindView(R.id.gv_history)
    GridView gvHistory;
    @BindView(R.id.iv_etclear)
    ImageView searchclear;
    @BindView(R.id.iv_delect)
    ImageView delect;
    @BindView(R.id.ll_hotsearchpag)
    LinearLayout ll_hotsearchpag;

    @BindView(R.id.history_list)
    ListView mHistotyListView;

    @BindView(R.id.rl_hothistory)
    RelativeLayout mHotSearchLayout;
    @BindView(R.id.search_history_title_layout)
    RelativeLayout mHistoryTitleLayout;
    private HotSearchHistoryAdapter mHistoryAdapter;

    @BindView(R.id.activity_search_status_layout)
    View mStatusLayout;
    /**
     * 历史搜索所需要的
     */
    //布局管理器
    private List<String> mShowHistotyData;

    private HotSearchGdAdapter gdAdapter;
    List<HotSearchDataModel.DataBean> mdata;

    private HistoryUtil mHistoryUtil;


    @Override
    public void setTheme() {

    }

    @Override
    public int setLayoutID() {
        return R.layout.activity_search;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        setBackButtonFinish();
        setSpecificTitleLayout(mStatusLayout);
        mHistoryAdapter = new HotSearchHistoryAdapter(this);
        mHistotyListView.setAdapter(mHistoryAdapter);
//        mHisToryMap = new LinkedHashMap<>();
        mShowHistotyData = new ArrayList<String>();
        mHistoryUtil = HistoryUtil.getInstance();
        mHistoryUtil.getHistoryFromLocal();
    }

    @OnClick({R.id.back, R.id.iv_delect, R.id.iv_etclear, R.id.et_search})
    public void OnClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.iv_delect:

                showClearAllDialog();
                break;
            case R.id.iv_etclear:
                etInputCitys.setText("");
                break;
            case R.id.et_search:
                if (!TextUtils.isEmpty(etInputCitys.getText())) {
                    searchclear.setVisibility(View.VISIBLE);
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void bindData() {
        gvHistory.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                HotSearchGdAdapter mAdapter = (HotSearchGdAdapter) parent.getAdapter();
                HotSearchDataModel.DataBean dataBean = (HotSearchDataModel.DataBean) mAdapter.getItem(position);
                etInputCitys.setText(dataBean.getSearch());
                startActivity(new Intent(HotSearchActivity.this, SearchActivity.class)
                        .putExtra("text", dataBean.getSearch()));
            }
        });
        etInputCitys.addTextChangedListener(watcher);
        etInputCitys.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    String aa = etInputCitys.getText().toString().trim();
                    if (!TextUtils.isEmpty(aa)) {
                        searchclear.setVisibility(View.VISIBLE);
                        delect.setVisibility(View.VISIBLE);
                        mHistoryUtil.setHistory(aa);
                        setHistotyAdapter();
                        startActivity(new Intent(HotSearchActivity.this, SearchActivity.class)
                                .putExtra("text", aa));
                    } else {
                        startActivity(new Intent(HotSearchActivity.this, SearchActivity.class)
                                .putExtra("text", ""));

                    }
                    KeyboardUtils.hideSoftInput(HotSearchActivity.this);
                }
                return false;
            }
        });
        mHistotyListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                HotSearchHistoryAdapter adapter = (HotSearchHistoryAdapter) parent.getAdapter();
                HisToryEntity hisToryEntity = (HisToryEntity) adapter.getItem(position);
                String searchContent = hisToryEntity.getHistoryContent();
                etInputCitys.setText(searchContent);
                mHistoryUtil.remove(searchContent);
                mHistoryUtil.setHistory(searchContent);
                setHistotyAdapter();
                startActivity(new Intent(HotSearchActivity.this, SearchActivity.class)
                        .putExtra("text", searchContent));
            }
        });
        mHistotyListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(final AdapterView<?> parent, View view, final int position, long id) {
                showConfirmDialog("", "是否删除本条历史记录", "删除", "取消", new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                        HotSearchHistoryAdapter adapter = (HotSearchHistoryAdapter) parent.getAdapter();
                        HisToryEntity hisToryEntity = (HisToryEntity) adapter.getItem(position);
                        String searchContent = hisToryEntity.getHistoryContent();
                        mHistoryUtil.remove(searchContent);
                        setHistotyAdapter();
                        sweetAlertDialog.cancel();
                    }
                });
                return true;
            }
        });

        mPresenter.getHotSearchGoods();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mHistotyList = mHistoryUtil.queryHistoy();
        if (mHistotyList != null && mHistotyList.size() > 0) {
            delect.setVisibility(View.VISIBLE);
            mHistoryTitleLayout.setVisibility(View.VISIBLE);
        }
        setHistotyAdapter();
    }

    @Override
    public void onUserLogin(LoginMessage loginMessage) {
    }

    private List<HisToryEntity> mHistotyList;
    @Override
    protected void onStop() {
        super.onStop();
        mHistoryUtil.savaHistoryToLocal();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mHistoryUtil.onDestory();
    }

    private TextWatcher watcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            searchclear.setVisibility(View.VISIBLE);
        }

        @Override
        public void afterTextChanged(Editable s) {
            searchclear.setVisibility(View.VISIBLE);
        }
    };


    //显示登录提示
    public void showClearAllDialog() {
        showConfirmDialog("", "确认要删除全部历史记录?", "确定", "取消",
                new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                        mShowHistotyData.clear();
                        mHistoryUtil.removeAll();
                        mHistoryAdapter.clear();
                        sweetAlertDialog.dismiss();
                        delect.setVisibility(View.GONE);
                        mHistoryTitleLayout.setVisibility(View.GONE);
                    }
                });
    }

    private void setHistotyAdapter() {
        mHistotyList = mHistoryUtil.queryHistoy();
        Collections.reverse(mHistotyList);
        mHistoryAdapter.setData(mHistotyList);
        if (mHistotyList.size() == 0) {
            delect.setVisibility(View.GONE);
            mHistoryTitleLayout.setVisibility(View.GONE);
        } else {
            if (delect.getVisibility() == View.GONE) {
                delect.setVisibility(View.VISIBLE);
            }
            if (mHistoryTitleLayout.getVisibility() == View.GONE) {
                mHistoryTitleLayout.setVisibility(View.VISIBLE);
            }
        }
//        }
    }

    @Override
    public void hotSearchList(HotSearchDataModel hotSearchDataModel) {
        if (hotSearchDataModel == null) {
            return;
        }
        if (hotSearchDataModel.getCode() != 200) {
            return;
        }
        mHotSearchLayout.setVisibility(View.VISIBLE);
        List<HotSearchDataModel.DataBean> mdatabean = hotSearchDataModel.getData();
        mdata = new ArrayList<>();
        for (int i = 0; i < mdatabean.size(); i++) {
            mdata.add(mdatabean.get(i));
        }
        gdAdapter = new HotSearchGdAdapter(mdata, HotSearchActivity.this);
        gvHistory.setAdapter(gdAdapter);
    }

    @Override
    public void loadDataComplated() {

    }

    @Override
    public void loadDataError() {

    }

    @NonNull
    @Override
    public AbBasePrecenter initPresenter() {
        return HotSearchMainPrecenter.create();
    }
}

